Python Virtual Environment for Django/Selenium Applications

The purpose of this article is to remind myself why you should create a Python Virtual Environment for all my projects. If it helps anyone else in debugging a suddenly broken test suite all the better.

Create a python virtual environment:

virtualenv –python=pythonexecutable destdir

Example

$ virtualenv --python=python3 ../virtualenv

Next step is switch the default to this. Firstly run the following command to test where the current locations is:

$ which python

/usr/local/bin/python
$ source ../virtualenv/bin/activate

where the location is an extension of what was chosen with the above “virtualenv” command.

$ which python

/my/folder/root/virtualenv/bin/python

Why virtual environments

Creating Virtual Environments allows you to install different versions of python modules for different projects. An example being that while going through the book “Test-Driven Development with Python” I was having issues suddenly with my functional tests. These began failing for no apparent reason. I then when back to previous commits in my git repository and found that all of them were not broken. It turned out that it had broken due to three things being updated. That being Django, Selenium and Firefox. I had to roll back all three of these.

(virtualenv) $ pip install django==1.8

[....]

(virtualenv) $ pip install selenium==2.52

[...]

The above commands will install Django version 1.8 and Selenium version 2.52 in your newly created virtual environment. If you run these commands without the version numbers the latest stable release will be installed. As of writing this article it was django 1.10 and selenium 3.1.

Now if you have a virtual environment setup you don’t have to worry about other projects upgrading your python setup and breaking anything. This is what had caused it in this case, I had upgraded all my python modules during development of another project.

Copyright © 2020 | Ben Hutton